import 'dart:io';

import 'package:FlutterStudy/model/post.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class PaginDataTableDemo extends StatefulWidget {
  @override
  _DataTableDemoState createState() {
    return _DataTableDemoState();
  }
}

class _DataTableDemoState extends State<PaginDataTableDemo> {
  HttpClient? _httpClient;

  int _sortColumnIndex = 0;

  bool _sortAscending = false;

  PageDataTableSource _postDataSource = PageDataTableSource();

  @override
  void initState() {
    super.initState();
    // 初始化 HttpClient 并配置证书验证回调
    _httpClient = HttpClient()
      ..badCertificateCallback = (X509Certificate cert, String host, int port) {
        // 返回 true 允许不安全的证书，生产环境应更谨慎处理
        return true;
      };
  }

  @override
  void dispose() {
    // 关闭 HttpClient 释放资源
    _httpClient?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return PaginatedDataTable(
      rowsPerPage: 5,
      horizontalMargin: 10,
      columnSpacing: 10,
      onSelectAll: (isAll) {
        debugPrint("check All");
        setState(() {
          posts.forEach((post) {
            post.selected = isAll!;
          });
        });
      },

      checkboxHorizontalMargin: 10,
      showCheckboxColumn: true,

      sortColumnIndex: _sortColumnIndex,
      sortAscending: _sortAscending,
      dataRowMinHeight: 80.0,
      // 设置数据行高度
      dataRowMaxHeight: 100,

      columns: [
        DataColumn(
          headingRowAlignment: MainAxisAlignment.center,
          onSort: (int columnIndex, bool ascending) {
            _sortPost(columnIndex, ascending);
          },
          label: Expanded(child: Text("标题")),
          numeric: false,

        ),
        DataColumn(
          headingRowAlignment: MainAxisAlignment.center,
          onSort: (int columnIndex, bool ascending) {
            _sortPost(columnIndex, ascending);
          },
          label: Text("作者"),
          numeric: false,

        ),
        DataColumn(
          headingRowAlignment: MainAxisAlignment.center,
          onSort: (int columnIndex, bool ascending) {
            _sortPost(columnIndex, ascending);
          },
          label: Text("图片"),
          numeric: false,

        ),
        DataColumn(
          onSort: (int columnIndex, bool ascending) {
            _sortPost(columnIndex, ascending);
          },
          label: Text("描述"),
          numeric: false,

        ),
      ],
      header: Text("分页table"),
      source: _postDataSource,
    );
  }

  void _sortPost(int columnIndex, bool ascending) {
    setState(() {

      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;

    });
    _postDataSource.sort(columnIndex,ascending);
  }
}

class PageDataTableSource extends DataTableSource {
  int _selectRowCount = 0;

  @override
  DataRow? getRow(int index) {
    /*   ;*/
    return DataRow.byIndex(
      selected: posts[index].selected,
      onSelectChanged: (se)=>debugPrint(""),
      index: index,
      cells: [
        DataCell(
          placeholder: true,
          Text(posts[index].title, style: TextStyle(fontSize: 10)),
        ),
        DataCell(Text(posts[index].author)),
        DataCell(
          Image.network(
            "https://img0.baidu.com/it/u=3153427856,187543907&fm=253&app=138&f=JPEG?w=889&h=500",
            width: 30,
            height: 30,
            loadingBuilder: (context, child, loadingProgress) {
              if (loadingProgress == null) return child;
              return CircularProgressIndicator();
            },
            errorBuilder: (context, error, stackTrace) {
              return Icon(Icons.error);
            },
          ),
        ),
        DataCell(
          Text(posts[index].description, style: TextStyle(fontSize: 10)),
        ),
      ],
    );
  }

  @override
  // TODO: implement isRowCountApproximate
  bool get isRowCountApproximate => false;

  @override
  // TODO: implement rowCount
  int get rowCount => posts.length;

  @override
  // TODO: implement selectedRowCount
  int get selectedRowCount => _selectRowCount;

  void sort(int columnIndex, bool ascending){
    // 根据列索引和排序方向对posts进行排序
    posts.sort((Post a, Post b) {
      switch (columnIndex) {
        case 0: // 标题列
          return ascending
              ? a.title.compareTo(b.title)
              : b.title.compareTo(a.title);
        case 1: // 作者列
          return ascending
              ? a.author.compareTo(b.author)
              : b.author.compareTo(a.author);
        default:
          return 0;
      }
    });
    notifyListeners();
  }

  void selectAll(bool selected){
    posts.forEach((it)=>it.selected=selected);
    notifyListeners();
  }
}
